<template>
  <div class="report-export">
    <!-- 报告选择 -->
    <div class="report-select-section">
      <div class="section-header">
        <i class="el-icon-document"></i>
        <span>选择要导出的报告</span>
      </div>
      
      <div class="select-all-box">
        <el-checkbox v-model="selectAll" @change="handleSelectAll">
          全选
        </el-checkbox>
        <span class="select-count">已选择 {{ selectedReports.length }} 份报告</span>
      </div>

      <div class="report-list">
        <div 
          v-for="report in reports" 
          :key="report.id"
          class="report-item"
        >
          <el-checkbox 
            v-model="report.selected"
          ></el-checkbox>
          <div class="report-info" @click="toggleReport(report.id)">
            <div class="report-header">
              <span class="report-name">{{ report.title }}</span>
              <el-tag :type="getStatusType(report.status)" size="mini">
                {{ report.status }}
              </el-tag>
            </div>
            <div class="report-meta">
              <span><i class="el-icon-document-copy"></i>{{ report.caseInfo }}</span>
            </div>
            <div class="report-meta">
              <span><i class="el-icon-time"></i>{{ report.investigateTime }}</span>
              <span><i class="el-icon-user"></i>{{ report.investigator }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 导出格式选择 -->
    <div class="export-format-section">
      <div class="section-title">
        <i class="el-icon-download"></i>
        <span>选择导出格式</span>
      </div>
      <div class="format-options">
        <div 
          v-for="format in exportFormats" 
          :key="format.type"
          class="format-card"
          :class="{ active: selectedFormat === format.type }"
          @click="selectedFormat = format.type"
        >
          <div class="format-icon" :style="{ backgroundColor: format.color }">
            <i :class="format.icon"></i>
          </div>
          <div class="format-name">{{ format.name }}</div>
          <div class="format-desc">{{ format.description }}</div>
        </div>
      </div>
    </div>

    <!-- 导出选项 -->
    <div class="export-options-section">
      <div class="section-title">
        <i class="el-icon-setting"></i>
        <span>导出选项</span>
      </div>
      <div class="options-list">
        <div class="option-item">
          <div class="option-label">
            <i class="el-icon-tickets"></i>
            <span>包含病例信息</span>
          </div>
          <el-switch v-model="exportOptions.includeCaseInfo"></el-switch>
        </div>
        <div class="option-item">
          <div class="option-label">
            <i class="el-icon-user"></i>
            <span>包含接触者信息</span>
          </div>
          <el-switch v-model="exportOptions.includeContacts"></el-switch>
        </div>
        <div class="option-item">
          <div class="option-label">
            <i class="el-icon-document-copy"></i>
            <span>包含处置措施</span>
          </div>
          <el-switch v-model="exportOptions.includeMeasures"></el-switch>
        </div>
        <div class="option-item">
          <div class="option-label">
            <i class="el-icon-picture"></i>
            <span>包含图片附件</span>
          </div>
          <el-switch v-model="exportOptions.includeImages"></el-switch>
        </div>
      </div>
    </div>

    <!-- 导出历史 -->
    <div class="export-history-section">
      <div class="section-title">
        <i class="el-icon-document-copy"></i>
        <span>最近导出记录</span>
      </div>
      <div class="history-list">
        <div 
          v-for="record in exportHistory" 
          :key="record.id"
          class="history-item"
        >
          <div class="history-icon" :style="{ backgroundColor: getFormatColor(record.format) }">
            <i :class="getFormatIcon(record.format)"></i>
          </div>
          <div class="history-info">
            <div class="history-title">{{ record.reportTitle }}</div>
            <div class="history-detail">
              <span class="format-name">{{ record.format }}</span>
              <span class="separator">·</span>
              <span class="file-size">{{ record.fileSize }}</span>
              <span class="separator">·</span>
              <span class="export-time">{{ record.exportTime }}</span>
            </div>
          </div>
          <div class="history-action">
            <el-button 
              type="text" 
              size="mini"
              icon="el-icon-download"
              @click="downloadFile(record)"
            >
              下载
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 导出按钮 -->
    <div class="action-buttons">
      <el-button 
        type="primary" 
        size="large"
        icon="el-icon-download"
        @click="handleExport"
        :disabled="selectedReports.length === 0"
      >
        导出报告（{{ selectedReports.length }}）
      </el-button>
    </div>

    <!-- 导出确认对话框 -->
    <el-dialog
      title="确认导出"
      :visible.sync="showExportDialog"
      width="90%"
      center
      custom-class="export-dialog"
    >
      <div class="export-confirm-content">
        <div class="confirm-info">
          <i class="el-icon-info"></i>
          <div class="info-text">
            <p>即将导出 <strong>{{ selectedReports.length }}</strong> 份报告</p>
            <p>导出格式：<strong>{{ selectedFormatName }}</strong></p>
          </div>
        </div>
        <div class="report-summary">
          <div class="summary-title">包含以下报告：</div>
          <div class="summary-list">
            <div 
              v-for="(report, index) in selectedReportsList" 
              :key="report.id"
              class="summary-item"
            >
              <span class="item-index">{{ index + 1 }}.</span>
              <span class="item-title">{{ report.title }}</span>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showExportDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmExport">确认导出</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getInvestigationReports,
  exportReport,
  batchExportReports,
  getExportHistory
} from './service';

export default {
  name: 'ReportExport',

  data() {
    return {
      reports: [],
      selectAll: false,
      selectedFormat: 'PDF',
      
      // 导出格式
      exportFormats: [
        {
          type: 'PDF',
          name: 'PDF文档',
          description: '便于阅读和打印',
          icon: 'el-icon-document',
          color: '#E6A23C'
        },
        {
          type: 'Word',
          name: 'Word文档',
          description: '可编辑文档格式',
          icon: 'el-icon-edit-outline',
          color: '#409EFF'
        },
        {
          type: 'Excel',
          name: 'Excel表格',
          description: '数据分析格式',
          icon: 'el-icon-s-grid',
          color: '#67C23A'
        },
        {
          type: 'HTML',
          name: 'HTML网页',
          description: '网页格式查看',
          icon: 'el-icon-monitor',
          color: '#909399'
        }
      ],

      // 导出选项
      exportOptions: {
        includeCaseInfo: true,
        includeContacts: true,
        includeMeasures: true,
        includeImages: false
      },

      // 导出历史
      exportHistory: [],

      // 对话框控制
      showExportDialog: false
    };
  },

  computed: {
    selectedReports() {
      return this.reports.filter(r => r.selected);
    },

    selectedReportsList() {
      return this.reports.filter(r => r.selected);
    },

    selectedFormatName() {
      const format = this.exportFormats.find(f => f.type === this.selectedFormat);
      return format ? format.name : '';
    }
  },

  watch: {
    reports: {
      handler() {
        const allSelected = this.reports.length > 0 && this.reports.every(r => r.selected);
        this.selectAll = allSelected;
      },
      deep: true
    }
  },

  methods: {
    // 获取状态标签类型
    getStatusType(status) {
      const typeMap = {
        '已完成': 'success',
        '进行中': 'warning',
        '待处理': 'info'
      };
      return typeMap[status] || 'info';
    },

    // 全选/取消全选
    handleSelectAll(value) {
      this.reports.forEach(report => {
        report.selected = value;
      });
    },

    // 切换报告选择
    toggleReport(reportId) {
      const report = this.reports.find(r => r.id === reportId);
      if (report) {
        report.selected = !report.selected;
      }
    },

    // 获取格式颜色
    getFormatColor(format) {
      const colorMap = {
        'PDF': '#E6A23C',
        'Word': '#409EFF',
        'Excel': '#67C23A',
        'HTML': '#909399'
      };
      return colorMap[format] || '#909399';
    },

    // 获取格式图标
    getFormatIcon(format) {
      const iconMap = {
        'PDF': 'el-icon-document',
        'Word': 'el-icon-edit-outline',
        'Excel': 'el-icon-s-grid',
        'HTML': 'el-icon-monitor'
      };
      return iconMap[format] || 'el-icon-document';
    },

    // 处理导出
    handleExport() {
      if (this.selectedReports.length === 0) {
        this.showToast('请先选择要导出的报告', 'warning');
        return;
      }
      this.showExportDialog = true;
    },

    // 确认导出
    confirmExport() {
      this.showExportDialog = false;

      const loading = this.$loading({
        lock: true,
        text: '正在导出，请稍候...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      const selectedIds = this.selectedReports.map(r => r.id);

      // 如果只有一个报告，使用单个导出
      if (selectedIds.length === 1) {
        exportReport(selectedIds[0], this.selectedFormat, this.exportOptions)
          .then((result) => {
            loading.close();
            this.$notify({
              title: '✅ 导出成功',
              message: `报告已导出为 ${result.fileName}`,
              type: 'success',
              duration: 3000,
              position: 'top-right',
              offset: 60
            });
            this.loadExportHistory();
            // 模拟下载
            this.simulateDownload(result.downloadUrl, result.fileName);
          })
          .catch(error => {
            loading.close();
            this.showToast(error.message || '导出失败', 'error');
          });
      } else {
        // 批量导出
        batchExportReports(selectedIds, this.selectedFormat)
          .then((result) => {
            loading.close();
            this.$notify({
              title: '✅ 导出成功',
              message: `${result.count} 份报告已打包导出`,
              type: 'success',
              duration: 3000,
              position: 'top-right',
              offset: 60
            });
            this.loadExportHistory();
            // 模拟下载
            this.simulateDownload(result.downloadUrl, result.fileName);
          })
          .catch(error => {
            loading.close();
            this.showToast(error.message || '导出失败', 'error');
          });
      }
    },

    // 模拟文件下载
    simulateDownload(url, fileName) {
      // 在实际项目中，这里会触发真实的文件下载
      console.log('Download:', url, fileName);
      this.showToast('文件下载已开始');
    },

    // 下载历史文件
    downloadFile(record) {
      this.showToast(`正在下载 ${record.reportTitle}`);
      // 模拟下载
      setTimeout(() => {
        this.showToast('文件下载已开始');
      }, 500);
    },

    // Toast提示
    showToast(message, type = 'success') {
      this.$notify({
        title: '',
        message: message,
        type: type,
        duration: 2000,
        position: 'top-right',
        offset: 60
      });
    },

    // 加载报告列表
    loadReports() {
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      getInvestigationReports().then(data => {
        this.reports = data.map(r => ({
          ...r,
          selected: false
        }));
        loading.close();
      }).catch(error => {
        loading.close();
        this.showToast(error.message || '加载失败', 'error');
      });
    },

    // 加载导出历史
    loadExportHistory() {
      getExportHistory().then(data => {
        this.exportHistory = data;
      }).catch(error => {
        console.error('加载导出历史失败', error);
      });
    }
  },

  mounted() {
    this.loadReports();
    this.loadExportHistory();
  }
};
</script>

<style scoped>
.report-export {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 80px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* 报告选择 */
.report-select-section {
  background: white;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  align-items: center;
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.section-header i {
  font-size: 20px;
  margin-right: 8px;
}

.select-all-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.select-count {
  font-size: 13px;
  color: #666;
}

.report-list {
  padding: 10px 15px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 400px;
  overflow-y: auto;
}

.report-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s;
}

.report-item >>> .el-checkbox {
  margin-right: 12px;
  margin-top: 2px;
  flex-shrink: 0;
}

.report-info {
  flex: 1;
  min-width: 0;
  cursor: pointer;
}

.report-info:active {
  opacity: 0.7;
}

.report-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.report-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 8px;
}

.report-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.report-meta i {
  margin-right: 3px;
  color: #409EFF;
}

/* 导出格式选择 */
.export-format-section {
  background: white;
  margin-bottom: 10px;
  padding: 15px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.section-title i {
  font-size: 18px;
  margin-right: 6px;
  color: #409EFF;
}

.format-options {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.format-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.format-card.active {
  background: #e7f4ff;
  border-color: #409EFF;
}

.format-card:active {
  transform: scale(0.95);
}

.format-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.format-icon i {
  font-size: 24px;
  color: white;
}

.format-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.format-desc {
  font-size: 12px;
  color: #999;
}

/* 导出选项 */
.export-options-section {
  background: white;
  margin-bottom: 10px;
  padding: 15px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.option-label {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #333;
}

.option-label i {
  font-size: 18px;
  margin-right: 8px;
  color: #409EFF;
}

/* 导出历史 */
.export-history-section {
  background: white;
  margin-bottom: 10px;
  padding: 15px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
}

.history-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-right: 12px;
}

.history-icon i {
  font-size: 20px;
  color: white;
}

.history-info {
  flex: 1;
  min-width: 0;
}

.history-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-detail {
  font-size: 12px;
  color: #999;
}

.separator {
  margin: 0 5px;
}

.history-action {
  margin-left: 10px;
  flex-shrink: 0;
}

/* 操作按钮 */
.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
  border-top: 1px solid #f0f0f0;
}

.action-buttons .el-button {
  width: 100%;
  border-radius: 6px;
  font-size: 15px;
  height: 46px;
  font-weight: 500;
}

/* 导出确认对话框 */
.export-confirm-content {
  padding: 10px 0;
}

.confirm-info {
  display: flex;
  align-items: flex-start;
  padding: 15px;
  background: #f0f9ff;
  border-radius: 8px;
  margin-bottom: 15px;
}

.confirm-info i {
  font-size: 24px;
  color: #409EFF;
  margin-right: 12px;
  flex-shrink: 0;
}

.info-text {
  flex: 1;
}

.info-text p {
  margin: 5px 0;
  font-size: 14px;
  color: #333;
}

.info-text strong {
  color: #409EFF;
  font-weight: 600;
}

.report-summary {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
}

.summary-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.summary-list {
  max-height: 300px;
  overflow-y: auto;
}

.summary-item {
  display: flex;
  align-items: flex-start;
  padding: 8px 0;
  font-size: 13px;
  color: #666;
}

.item-index {
  margin-right: 8px;
  color: #999;
  flex-shrink: 0;
}

.item-title {
  flex: 1;
  line-height: 1.4;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  padding: 0;
}

.dialog-footer .el-button {
  flex: 1;
  margin: 0;
}
</style>

